ASP.NET ClientID & jQuery small trick

February 8, 2010

Up to ASP.NET 3.5 the client ids for .NET controls is not for passionate readers it looks like this: “ctl00_ctl00_decoratedArea_contentArea_homeSearch_mileageDropDownRow”
On the other hand the client name is “ctl00$ctl00$decoratedArea$contentArea$homeSearch$mileageDropDownRow” so this does not really help.

If you have to reference this from client code:
1) Migrate to asp.net 4.0 ( best option )
2) Use <%controlName.ClientID %>, but this only applies in a aspx or ascx file

If you are writing code in a js file there is no easy way, but the jquery to the resque!
Just use selector like this $(‘id$=shortServerId’)
This selects all elements which have attribute id ending with ‘shortServerId’ and returns them as array. If you want to apply non-jquery code to your selection as normal DOM functions first reference to array element of choice like this.

var allElements = $('id$=shortServerId');
if(allElements.length > 0) {
    yourDomFunciton(allElements[0]);
}

Needless to say it is a lot better to make yourself a favor and use only jQuery for  DOM modifications.

References
http://weblogs.asp.net/asptest/archive/2009/01/06/asp-net-4-0-clientid-overview.aspx
http://weblogs.asp.net/dotnetstories/archive/2009/10/27/asp-net-4-0-and-clientid-mode.aspx

The C/C++ Programming languages obsolete?

February 6, 2010

Recently I have heard opinions of some developers
“There is no big loss that one haven’t programmed in C/C++”
“C is useless now days, there is no point of learning it”

Nothing could more far from the truth.
I would like to point out that I am 28 year old and consider myself young. Despite of this I am glad that I do know C/C++ and have worked extensively with these languages. Knowledge of the C and C++ have given me deep understanding of how computer programming works in general and even now that I do not use them any more I am still applying most of the principles on daily basis.

It is important to understand that every programming language that you know gives you new view of things and affects your way of thinking if you aren’t actually using it. It would be best if every developer knows C, one functional language, one scripting language.

So you are C# or Java developer and you think you do not need C/C++ because they are “useless”
Can you answer following questions:
– In what language is written the operating system that you are using ( be it Windows, Linux, BSD, Solaris)
– In what language is written the C#/Java runtime
What about the database, the web server?
I could go on and on but you I think you see my point.

C/C++ is used in almost everything you use and probably will never be obsolete. Even if you don’t use it you actually NEED to learn it ( and not just C/C++) in order to be a good developer no matter what language you are currently programming in.

How to detect UTF8 encoded text

February 6, 2010

What is UTF8 encoding and how to detect it?

You can find UTF8 specification documents at the end of this post.

The long story short UTF8 is a unicode text representation that may use one to four bytes to represent a single text character.

How to detect it?
First the easy solution would be to check for the Byte Order Mark at the beginning. For UTF8 it is: ef bb bf.
However a lot of UTF8 files do not use it and generally Unix/Linux programs do not ust UTF8 with BOM and some of them may not handle it well.

So how to detect UTF8 without BOM?

Basically check up the file if it only contains byte sequences list in the following table:

00..7F	 	 	 
C2..DF	80..BF 	 	 
E0	A0..BF	80..BF 	 
E1..EF	80..BF	80..BF 	 
F0	90..BF	80..BF	80..BF
F1..F3	80..BF	80..BF	80..BF
F4	80..8F	80..BF 	80..BF

I have created little c# library that does exactly this:
http://www.codeplex.com/utf8checker

There are unit tests too using some extensive utf8 sample files.

Feedback and questions welcome!

Rerefences

http://www.unicode.org/versions/corrigendum1.html

http://www.ietf.org/rfc/rfc2279.txt

http://anubis.dkuug.dk/JTC1/SC2/WG2/docs/n1335

http://www.cl.cam.ac.uk/~mgk25/unicode.html

Spam & Fraud Prevention

February 25, 2009

Objective: we want to prevent spam send from our contact form.

Let’s look at the problem a little closer. What kinds of spam are there?

1. Messages send from a bot issuing direct http requests

How the prevent this:

Using javascript and/or css detectionn should be pretty successful to kick this kind of bots out. For javascript prevention we could make the client to submit  the result of an artithmetic expression ( easier to crack ) or dom manipulation back to us.

2. Messages send from a bot automating the browser

How to prevent this:

Since these bots are using full blown browser they can’t be beaten with javascript tricks, because they have this. The impact isn’t that big, because using the browser they could probaly just send about 10 Emails per minute opposed to a couple hundred or thousand if sending direct http requests. However 10 Emails per minute isn’t that little.  What to do:

One Idea would be to measure time needed to submit a form. It is less than 10 seconds – kick it, its a bot.

3. Spam send by real people

This is the hardest one to beat, it is actually unbeatable.  The only think you can do to display captcha with increasing number of characters to type for each sent email. So if someone sends 5 Emails it would be OK,  but after 10-15 Emails it is going to get slower and slower for him.

BASTA! 2009 Konferenz

February 25, 2009

Diese Woche bin ich auf der BASTA! .NET Konferenz in Darmstadt und ich würde diese Konferenz weiter empfehlen. Es bieten sich einige sehr gute Möglichkeiten sich mit Kollegen auszutauschen und über neue Technologien informieren.

Eine echte Herausforderung bei den meisten Konferenzen ist welche Vorträge man auswählen soll, wenn zu jedem Zeitpunkt 6 gleichzeitig laufen und die Hälfte davon ist interessant und/oder relevant.

Ein Paar Tipss dazu:

  • Der Speaker ist genau so wichtig, wie das Thema, oder sogar noch wichtiger. Ein herrvorragender Vortrag zum “unwichtigen” Thema bring wesentlich mehr,  als  ein schlechter Vortrag  zum top aktuellen Thema
  • Beschränken Sie sich nicht nur auf Technologien, die Sie bei dem jetzigen Job einsetzen, oder einsetzen werden. Ein breites Technologieportofolio gehört zu dem Entwicklerberuf
  • Besuchen Mal eine oder andere nicht technologisch bedingte Präsentation. Kenntnisse in Sachen wie Selbstorganization, Projekt Management, Schätzung sind oft viel wichtiger. Bonus:  Wissen in diesen Bereichen ist auch nach 20 Jahren nicht veraltet.

MCTS is Microsoft Certified Technology Specialist

February 10, 2009

I’m now Microsoft Certified Technology Specialist for ASP.NET 3.5
after I passed the second exam
70-562 TS: Microsoft .NET Framework 3.5, ASP.NET Application Development

MTS ASP.NET 3.5 Logo

Back to basics – the law of leaky abstractions

November 30, 2008

Back to basics – the law of leaky abstractions

When developing web applications we use high-level web frameworks and full featured controls that abstract generating the html output for us. It is however always useful to know, that what html gets generated.
Every now that I see ASP.NET code, that uses LinkButton, which posts back to the server just to redirect to the link url, issuing two http requests for something, that can be achieved with a simple html anchor.

Knowing what your framework or compiler generates was always useful. Is it an old saying, that the good C programmer knows the assembly generated by the compiler. These days seeing and understanding the html source, generated from your framework is a lot easier, so do it.

“The law of leaky abstractions” is a classical software development article by Joel Spolsky
http://www.joelonsoftware.com/articles/LeakyAbstractions.html

Dependeny Injection vs Encapsulation

November 24, 2008

Dependency Injection vs Encapsulation

When trying to show coworkers of the advantages of Dependency Injection I often encounter the argument, that it hurts one of the major object-oriented principles – encapsulation.

Let us consider the following basic example of class that has two dependencies, created in the constructor:

public class SomeClass
{
	IWriter writer;
	ILogger logger;

	public SomeClass()
	{
		this.writer = new StreamWriter();
		this.logger = new RegistryLogger();
	}
}

Client code:

SomeClass someClass = new SomeClass();

SomeClass has direct dependencies and can’t be used without them and is clearly not testable. Let us see a implementation with dependency injection:


public class SomeClass : ISomeClass
{
	IWriter writer;
	ILogger logger;

	public SomeClass(IWriter writer, ILogger logger)
	{
		this.writer = writer;
		this.logger = logger;
	}
}

This is clearly much better, but is considered to be violating the encapsulation principle form some developers. Encapsulation principle tells us to hide the class inner workings form the user. This is important in order to allow us to change the class implementation without changing all of its clients. This is a valid point, that I respect, we all strive to the “low maintenance road” (Ayende) – the most important thing in software development.

However let us look at the client code and see if it actually breaks the encapsulation principle:

ISomeClass someClass = Container.Resolve<ISomeClass>();

What we see here is that, the client code does not even know a damn thing about the class dependencies!
We just let the dependency injection container do the heavy lifting for us and don’t worry how to create all of the class dependencies.
In practice we actually do not even have the possibility to use the constructor!
That’s true – in production code instantiating a class from the constructor would require creating all of its dependencies, which would require instantiating their dependencies and so on. It would be safe to say, that the developers can’t even use the constructor and must instantiate their objects using the dependency injection container, which is so much easier.

So the user of the code does not actually even know what kind if dependencies a class has – all of this because of the dependency injection container. So actually instead of breaking encapsulation we are driving it to a whole new level – each individual class does not get to decide what kind of object it needs – everything gets configured in the configuration of the container. This definitely does not break the encapsulation principle. It makes it hold even stronger.

As a side note I want to point out, that I am definitely against the point of view “If you let the developers to bad things, then they will”. If you don’t trust your developers you shouldn’t hire them in the first place. Treat all the of the developers as stars and they will be.

Happy dependent less programming!

Web Integration Tests – with or without the browser

November 24, 2008

In this post, I would like to go in the topic of web tests – automatically verifying the functionality of a full deployed web site.
Automating the browser has been a popular approach, which gives the benefit of testing the site, as the user sees it, including images, css files and secondary functionality implemented with javascript as Ajax.
Internet Explorer can be automated through its COM API – this is a popular approach that is being used by several open source and commercial libiraries like watin and watir.
Other innovative way is taken from the selenium framework, which uses javascript to simulate user actions, which makes it portable across browsers and operating systems.

Automating the browser there is one big problem though – the tremendous amount of web requests issued for loading the complete page, including all images, css files, ad banners and so on, which can be a big performance hit if you have a lot of tests. While it is important to verify, that everything is properly deployed, all images are found and so on, the loading of all this secondary clutter does not provide any benefit for the functional tests and just slows the execution time.
When the tests run for several hours it is very difficult to use them as a feedback mechanism about the project status. Slow tests aren’t used by the developers and at the end, aren’t used at all and provide little or no value the project.

Confronted with this problem the test engineering team at AutoScout took another approach – testing without the browser, using direct http requests. This technique appears a little more challenging to use, but cuts the tests execution time by orders of magnitude. Our http tests run for a minute and half and provide very fast and reliable feedback, which makes them very useful.

If you want to use direct http tests there are several ways to write them – for .NET you can use the MS Test library that ships with Microsoft Visual Studio Testing Edition, or the HttpWebRequest/HttpWebResponse classes in the System.Net namespace. For MS Test library you have to install Visual Studio Tester Edition on your build servers.
For java there is the HttpClient package from apache. We ended up using our own small http implementation, optimized for testing purposes.
If there is interest about it, I would gladly go into more detail about it.

I would like to point out, that using direct http test requests does not replace browser tests when comes to testing ajax functionality and deployment issues of the secondary files. Our advice would be to use direct http tests when you can and browser tests when you have to. Combining the best of both worlds has given us satisfying test coverage and feedback speed.

Happy testing!

Unit Tests 101 – how to write testable code

November 22, 2008

Reposting this entry I wrote for my company’s blog

Hi, I am Test Engineer at AutoScout24 in Munich and will be writing about Unit Tests, testability, Acceptance Tests and developing high quality software. In this post I want to go in go into the testability topic – what makes code testable and what not. It may seem obvious how to do it for the people, that are going the TDD way, but sometimes it is hard for new developers to adopt the art of writing Unit Tests.
Writing Unit Tests is all about being able to use the classes you develop in isolation, without having to instantiate their external dependencies, or a database, filesystem, webserver or something else running.
So it all boils down to the question – how to make the class dependencies exchangeable. Let’s assume we have the following code:

Code:

public class ClassInTest {
 public bool DoStuff() {
   IExternalDependency dependency = new ExternalDependency(...);
   return dependency.Something();
 }
}

Unit Test:
impossible to write

For this example we have pretty simple code to test and just want to concentrate in making it testable.
The main issue with this code is that, the class instantiates the ExternalDependency by itself. Considering that when writing an Unit Test we are interested in the functionality of ClassInTest only, we would like to ignore the ExternalDependency and replace it with some kind of fake implementation

The first approach would be to encapsulate the object instantiation with a static method within the class.

Code:

public class ClassInTest {

  static IExternalDependency dependency;

  public static IExternalDependency CreateExternalDependency(...) {
    if(dependency == null) {
      dependency = new ExternalDependency(...);
    }
    return dependency;
  }

   public static void SetExternalDependency(IExternalDependency aDependency) {
     dependency  = aDependency;
   }

   public bool DoStuff() {
     IExternalDependency dependency = CreateExternalDependency(...);
     return     dependency.Something();
   }
}

Unit Test:
public class ClassInTestTest {
  public void DoStuffTest() {
    IExternalDependency mock = new Mock<IExternalDependency>();
    mock.Expect(x => x.Something()).Returns(true);
    ClassInTest.SetExternalDependency(mock.Object);

    ClassInTest classInTest = new ClassInTest();
    Assert.IsTrue(classInTest.DoStuff());
  }
}

To go one step further we could write a class responsible only for object creation – a factory.

Code:

public class ClassInTest {

  public bool DoStuff() {
    IExternalDependency dependency = CreateExternalDependency(...);
    return     dependency.Something();
  }
}

public class ClassInTestFactory {
  static IExternalDependency dependency;

  public static IExternalDependency CreateExternalDependency(...) {
    if(dependency == null) {
      dependency = new ExternalDependency(...);
    }
    return dependency;
  }
}

  public static void SetExternalDependency(IExternalDependency aDependency) {
    dependency  = aDependency;
  }
}

Unit Test:
public class ClassInTestTest {
  public void DoStuffTest() {
    IExternalDependency mock = new Mock<IExternalDependency>();
    mock.Expect(x => x.Something()).Returns(true);
    ClassInTestFactory.SetExternalDependency(mock.Object);

    ClassInTest classInTest = new ClassInTest();
    Assert.IsTrue(classInTest.DoStuff());
   }
}

This way we have clean separation between classes, that know how to create objects and classes who do the actual work. As a side effect we have to write a factory class for every second class in the application.

The last and clearly the best approach we are going to examine is the dependeny injection path – let all the wiring work to an external container, which knows how to create all registered classes and do not bother writing code for this yourself, be it a static method within the class or factory. The point is to have each class to declare its dependencies in the constructor or as properties

Code:

public class ClassInTest {
  public ClassInTest(IExternalDependency dependency) {
    this.dependency = dependency;
  }

  public bool DoStuff() {
    return     dependency.Something();
  }
}

Unit Test:
public class ClassInTestTest {
  public void DoStuffTest() {
    IExternalDependency mock = new Mock<IExternalDependency>();
    mock.Expect(x => x.Something()).Returns(true);

    ClassInTest classInTest = new ClassInTest(mock.Object);
    Assert.IsTrue(classInTest.DoStuff());
  }
}

This is clearly less code and makes it easier to test, the important thing is to examine the client code – how is ClassInTest used in production, without the container:

Client Code without usage of dependency injection container:

ClassInTest classInTest = new ClassInTest(new ExternalDependency());

In real life when you have a lot of dependencies, each of them having a lot of other dependencies it is very hard burden to pass all the arguments by yourself. Let the container do it for you.

Client with dependancy injection:

ClassInTest classInTest = container.Resolve<ClassInTest>();

Notice that you don’t have to bother what does the ClassInTest need to be instantiated. The “magic” is that IExternalDependency is registered within the container, so we just request some object and let the container do the heavy lifting – examining what constructors it has and resolving the needed arguments.

If are you looking for dependency injection container you can try AutoFac, Castle Windsor, StructureMap or Microsoft Unity, just to name a few.

It is not always possible to switch to dependency injection in a large project – then factories are you best choice. But keep in mind, that dependency injection is the way to go and do your best to prepare your project for it.

Happy programming!

Invoking PowerShell from cmd.exe

November 22, 2008

Microsoft PowerShell is a marvelous technology, and according to some linux developers the only reason they are jealous of not working  on Windows 🙂

Being so powerfull, I wanted to use it in our build script, but unfortunately it was hard to invoke a powershell script from the command line – cmd.exe.
Surprisingly there is no command line option for executing scripts, which is obvious to me and probably  one of the most important use cases.
After struggling for a while I finally found a blog post about it and want to spread the word and maybe help someone with the same problem
So here it is:

powershell " & 'C:\path\to\script.ps1' "

Invoked with one argument in quotes, powershell executes the string as script. So the trick here is to invoke it, and use the & ‘script_file.ps1’ command to make it execute your script.

http://www.leeholmes.com/blog/RunningPowerShellScriptsFromCmdexe.aspx

Good luck everyone and happy programming!

Detection of product failed during request for component

April 17, 2008

If your MSI Installation package is bringing that error message I might have a solution for you. It applies only if you are authoring the installation, your product doesn’t use the resiliency feature and you know what are you doing.

First the theory – each and every COM component, that your installation is registering becomes a little feature with it – every time it is used Windows Installer is going to check if something has gone wrong with it, if so repair installation is started. This brings a lot more problems than it solves, especially if you know, that the updated COM component, is still valid.

So how to “Stop Installation Idiocy”?
My solution was to remove the extra information registered with each COM component, so the Windows Installer has no way to monitor it and as end result can’t bring up an error message if something has changed with the component.  This resiliency feature may be useful in some occasions, but our product does not rely on it in any way and it is just a source of endless problems when we ship updated component.

Here is sample code for a custom action in InstallScript, you can do the same in C++ no matter how are you building your MSI package.
The idea is to find out which COM components are you registering and to remove the hash values, that are inserted automatically from Windows Installer.

function RemoveRepairKeys(hMSI)
	STRING key, guid, context;
	LONG hDB, hView, hRec, r;
	NUMBER pos, num;
begin
	RegDBSetDefaultRoot(HKEY_CLASSES_ROOT);

	hDB = MsiGetActiveDatabase(hMSI);

	if(hDB = 0) then
		SprintfMsiLog("Error MsiGetActiveDatabase");
		return 0;
	endif;

	PrintStatus(
             MsiDatabaseOpenView(hDB, "SELECT `Key` FROM `Registry` WHERE `Root`=0", hView),
             "MsiDatabaseOpenView"
        );
	PrintStatus(MsiViewExecute(hView, 0), "MsiViewExecute");
	r = MsiViewFetch(hView, hRec);
	PrintStatus(r, "MsiViewFetch");
	RegDBSetDefaultRoot(HKEY_CLASSES_ROOT);
	num = 260;
	while(r == 0)
		r = MsiRecordGetString(hRec, 1, key, num);
		pos = StrFindEx(key, "CLSID\\", 0);
		if(pos >= 0) then
			SprintfMsiLog("GUID %s", guid);
			StrSub(guid, key, pos + 6, 38);
			LogResult(RegDBDeleteValue(
				"\\CLSID\\" + guid + "\\InprocServer32", "InprocServer32"),"\\CLSID\\"
                                + guid + "\\InprocServer32.InprocServer32"
			);
			LogResult(
				RegDBDeleteValue("\\CLSID\\" + guid + "\\LocalServer32", "LocalServer32"),
				"\\CLSID\\" + guid + "\\LocalServer32.LocalServer32"
			);
		endif;

		MsiCloseHandle(hRec);
		r = MsiViewFetch(hView, hRec);
		//PrintStatus(r, "MsiViewFetch");
	endwhile;

	PrintStatus(
              MsiDatabaseOpenView(hDB, "SELECT `CLSID`, `Context` FROM `Class`", hView),
             "MsiDatabaseOpenView");
	PrintStatus(MsiViewExecute(hView, 0), "MsiViewExecute");
	r = MsiViewFetch(hView, hRec);
	PrintStatus(r, "MsiViewFetch");
	RegDBSetDefaultRoot(HKEY_CLASSES_ROOT);
	num = 260;
	while(r == 0)
		r = MsiRecordGetString(hRec, 1, guid, num);
		r = MsiRecordGetString(hRec, 2, context, num);
		LogResult(
			RegDBDeleteValue("\\CLSID\\" + guid + "\\" + context, context),
			"\\CLSID\\" + guid + "\\" + context  + "." + context
		);
		MsiCloseHandle(hRec);
		r = MsiViewFetch(hView, hRec);
		//PrintStatus(r, "MsiViewFetch");
	endwhile;

	PrintStatus(MsiCloseHandle(hView), "MsiCloseHandle");

	DeleteRepairKeysFixed(hMSI);
end;

Use this at your own risk, it did work for us pretty well. Questions and comments are welcome.

Some links regarding the resiliency feature:

http://blogs.msdn.com/astebner/archive/2005/01/13/352649.aspx
http://blogs.msdn.com/astebner/archive/2004/08/24/219764.aspx
http://blogs.msdn.com/windows_installer_team/archive/2005/11/01/486587.aspx
http://www.installsite.org/pages/en/msifaq/a/1037.htm

Delphi/C++ Builder vs .NET and C#

February 26, 2008

Lately I was looking for a nice GUI front-end for MySql and also for Sqlite. MySql now comes with several GUI Tools, including MySql Query Browser which is supposed to do exactly what I need – except, that it doesn’t.
Some features simply aren’t just there – what about clicking in data cell to edit its value? Too advanced to be required from a application being developed for at least two years or even more? And I was thinking that Database GUI editors were all about editing data.

Than I tried the open source HediSql. It is truly awesome! Given the enormous competition in the field, and official GUI from MySql itself these guyes just rock!
It gives you everything that you need; it is fast, responsible and nice to work with. Keep up the good work! What about Sqlite support?

It was clear that it is native application – it just worked too smooth and had too small memory footprint to be developed with .NET.
A wanted to look at the source and to my surprise it wasn’t in C++, it was Delphi!
That really got me thinking – some of the best software products, that I have used – BSPlayer, Skype, HeidiSql, TestComplete– just to name a few, aren’t developed in a mainstream language like C++ or C#, but in Deplhi. I even was told, that the initial version of the eBay ISAPI was also developed in Delphi.
But there is more – a lot of bussines applications, that really make a lot of money for their developers are also developed also in Delphi.

We had a presentation at work from a partner software company, which product works with ours. He talked all day long and he could show us just a small part the application features. It was really good and he developed it all by himself. Guess what development platform he is using – Delphi.

Well I don’t know why Microsoft can’t pull this off with all the billions they are putting in to their development platform. .NET is really good, I love developing software with it, but I hate using .NET products, because they are slow. Not too slow if the developers did a good job, but a lot slower than anything native.

I know that there is no market for Delphi developers and I know that Java and .NET jobs are all around the place, but Delphi and C++ Builder are better for developing user software.

So if you are looking for career opportunities – go .NET or J2EE. But if you want to develop a software product and sell it successfully – Deplhi and C++ Builder are the way to go.

I wish I had the courage to use this platform way myself.

memccpy considered harmful ( if you don’t know how to use it)

February 26, 2008

Ever heard of the memccpy function?

It is very similar to memcpy, but it will stop copying if given delimiter character is encountered. So that’s a nice feature – let’s just use it instead of memcpy everywhere!

Except that you must pay extreme attention to what are you actually copying, and what kind of delimiter character are you using. Copying text strings and using line feed ‘n’ as delimiter is fine, but copying mac addresses, and using ‘n’ as delimiter, as a coworker did, is not.
But why, you may ask. Well because the ‘n’ character, 0x0a in hex, is pretty valid byte to come in a mac address. And guess what – if you use memccpy to copy a mac address and use ‘n’ as delimiter, it is going the get truncated! And because the target buffer is already allocated with certain size and filled with some random data, that may also be valid for mac address, this kind of error may go unnoticed for a long time.

This brings up the question of the data representation, that you are using and how well you understand it, and also the quality of the interface definitions of common C functions and stuff like:

if(strcmp(str1, str2)) {
/* if you expect to get here
if str1 and str2 are the same,
you are in for a surprise
*/
}

Otherwise remember it also very important to always check the return values, that you are getting and event more important also: test, test, test Read the rest of this entry »

GUIDs, their representation and Base64

February 26, 2008

Everyone knows what a GUID is – 128 bit number, that is supposed to be global unique and it is used for identifier for different types of objects, COM objects most notably.
Usually they are formatted as hex string like {F7F052A2-8BC7-4b84-8330-228BCA8A6E19}. A tool for
creating guids can is guuidgen.exe, there are also System.Guid class and CoCreateGuid API.
Sometimes GUIDs have to be formatted more compactly, for instance in the IFC Specification GUIDs have to be formatted as Base64, making them string with 22 characters length.
Sadly the base64 encoding is non-compatible with the .NET implementation, which makes it a hard task to convert System.Guid object to required format.
IFC Base64 is using 0-9A-Za-z_$ characters and .NET implementation is using something like A-Za-z0-9 for encoding table.
There is some sample C code on the ifc wiki site, so I went for the easy solution – make a dll and call it from .NET.
The problems with this approach kept comming one after another – mostly dll was not always found in Web scenario, due to deployment issues. But there are also other possible hurdles – 64bit migration, deployment on Mono and so on.
So I needed a pure managed implementation of Base64 encoding for GUIDs.
Some googling brought me to sample code, that I adjusted it to the spec and here is the solution:

public class Managed {

  public static string GetId(Guid guid) {
    return ToBase64String(guid.ToByteArray());
  }

  public static string GetId() {
    return ToBase64String(Guid.NewGuid().ToByteArray());
  }

  public static readonly char[] base64Chars = new char[]
  { '0','1','2','3','4','5','6','7','8','9',
  'A','B','C','D','E','F','G','H','I','J','K','L','M',
  'N','O','P','Q','R','S','T','U','V','W','X','Y','Z',
  'a','b','c','d','e','f','g','h','i','j','k','l','m',
  'n','o','p','q','r','s','t','u','v','w','x','y','z',
  '_','$' };

  public static string ToBase64String(byte[] value) {
    int numBlocks;
    int padBytes;

    if ((value.Length % 3) == 0) {
      numBlocks = value.Length / 3;
      padBytes = 0;
    } else {
      numBlocks = 1 + (value.Length / 3);
      padBytes = 3 - (value.Length % 3);
    }
    if (padBytes < 0 || padBytes > 3)
      throw new ApplicationException("Fatal logic error in padding code");

    byte[] newValue = new byte[numBlocks * 3];
    for (int i = 0; i < value.Length; ++i)
      newValue[i] = value[i];

    byte[] resultBytes = new byte[numBlocks * 4];
    char[] resultChars = new char[numBlocks * 4];

for (int i = 0; i < numBlocks; i++) {
  resultBytes[i * 4 + 0] = 
       (byte)((newValue[i * 3 + 0] & 0xFC) >> 2);
  resultBytes[i * 4 + 1] =
       (byte)((newValue[i * 3 + 0] & 0x03) << 4 |
       (newValue[i * 3 + 1] & 0xF0) >> 4);
  resultBytes[i * 4 + 2] =
        (byte)((newValue[i * 3 + 1] & 0x0F) << 2 |
        (newValue[i * 3 + 2] & 0xC0) >> 6);
  resultBytes[i * 4 + 3] =
        (byte)((newValue[i * 3 + 2] & 0x3F));
 }

 for (int i = 0; i < numBlocks * 4; ++i)
   resultChars[i] = base64Chars[resultBytes[i]];

   string s = new string(resultChars);
   return s.Substring(0, 22);
 }
}

So if you have to encode something as Base64 or deal with GUIDs with one way or another – this may be helpful to you.
Original code by James McCaffrey Read the rest of this entry »